<template>
  <div class="creation-container">
    <el-card shadow="hover" class="creation-card">
      <template #header>
        <div class="card-header">
          <h1 class="title">
            <el-icon class="title-icon"><Edit /></el-icon>
            文字创作
          </h1>
        </div>
      </template>

      <el-form ref="form" :model="formData" label-width="100px" class="creation-form">
        <el-form-item label="标题" prop="title">
          <el-input
              v-model="formData.title"
              placeholder="请输入标题"
              size="large"
              :prefix-icon="Document"
          ></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
              type="textarea"
              v-model="formData.content"
              :rows="8"
              placeholder="请输入内容"
              resize="vertical"
              show-word-limit
              maxlength="1000"
          ></el-input>
        </el-form-item>

        <el-form-item label="AI创作">
          <el-card shadow="never" class="sub-card">
            <el-row :gutter="15">
              <el-col :span="18">
                <el-input
                    v-model="askText"
                    placeholder="请输入AI创作提示词"
                    :prefix-icon="ChatDotRound"
                ></el-input>
              </el-col>
              <el-col :span="6">
                <el-button
                    type="primary"
                    @click="aiAskTxt"
                    size="large"
                    :icon="MagicStick"
                    class="full-width-btn"
                >
                  AI创作
                </el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-form-item>

        <el-form-item label="类型">
          <el-select
              v-model="formData.type"
              placeholder="请选择类型"
              style="width: 100%"
              size="large"
          >
            <el-option value="故事" label="故事">
              <span style="float: left">
                <el-icon><Reading /></el-icon> 故事
              </span>
            </el-option>
            <el-option value="诗歌" label="诗歌">
              <span style="float: left">
                <el-icon><Notebook /></el-icon> 诗歌
              </span>
            </el-option>
            <el-option value="祝福语" label="祝福语">
              <span style="float: left">
                <el-icon><ChatLineSquare /></el-icon> 祝福语
              </span>
            </el-option>
            <el-option value="活动" label="活动">
              <span style="float: left">
                <el-icon><Calendar /></el-icon> 活动
              </span>
            </el-option>
            <el-option value="文章" label="文章">
              <span style="float: left">
                <el-icon><Document /></el-icon> 文章
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="配图上传">
          <el-card shadow="never" class="sub-card">
            <el-upload
                action=""
                :auto-upload="false"
                :on-change="handleFileUpload"
                :show-file-list="false"
                accept="image/*"
                class="upload-demo"
            >
              <el-button type="primary" :icon="Upload">
                选择图片
              </el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持 jpg、png 格式，大小不超过 5MB
                </div>
              </template>
            </el-upload>
            <div v-if="uploadedImageUrl" class="image-preview">
              <el-image
                  :src="uploadedImageUrl"
                  class="thumbnail"
                  alt="预览图"
                  :preview-src-list="[uploadedImageUrl]"
                  fit="cover"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="preview-actions">
                <el-button type="danger" size="small" @click="removeUploadedImage" :icon="Delete">
                  移除
                </el-button>
              </div>
            </div>
          </el-card>
        </el-form-item>

        <el-form-item label="AI作图">
          <el-card shadow="never" class="sub-card">
            <el-row :gutter="10" class="mb-2">
              <el-col :span="12">
                <el-input
                    v-model="askImgText"
                    placeholder="请输入作图描述"
                    :prefix-icon="Picture"
                ></el-input>
              </el-col>
              <el-col :span="6">
                <el-select v-model="imageCount" placeholder="选择张数">
                  <el-option value="1" label="1张"></el-option>
                  <el-option value="2" label="2张"></el-option>
                  <el-option value="3" label="3张"></el-option>
                  <el-option value="4" label="4张"></el-option>
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-button
                    type="primary"
                    @click="aiAskImg"
                    class="full-width-btn"
                    :icon="DataAnalysis"
                >
                  AI作图
                </el-button>
              </el-col>
            </el-row>
            <div v-if="imageUrls.length > 0" class="images-preview">
              <div v-for="(imgUrl, index) in imageUrls" :key="index" class="image-item">
                <el-image
                    :src="imgUrl"
                    class="thumbnail"
                    alt="AI生成图"
                    :preview-src-list="imageUrls"
                    fit="cover"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="preview-actions">
                  <el-button type="danger" size="small" @click="removeImage(index)" :icon="Delete">
                    移除
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-form-item>

        <el-form-item label="标签">
          <el-card shadow="never" class="sub-card">
            <!-- 默认标签区域 -->
            <div class="default-tags">
              <span class="tag-section-title">推荐标签：</span>
              <el-tag
                  v-for="tag in defaultTags"
                  :key="tag"
                  class="default-tag"
                  @click="addDefaultTag(tag)"
                  :type="formData.tags.includes(tag) ? 'primary' : 'info'"
                  :class="{ 'disabled': formData.tags.length >= 5 && !formData.tags.includes(tag) }"
                  effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>

            <!-- 已添加标签区域 -->
            <div class="added-tags">
              <span class="tag-section-title">已选标签：</span>
              <el-tag
                  v-for="(tag, index) in formData.tags"
                  :key="index"
                  closable
                  type="primary"
                  effect="light"
                  @close="formData.tags.splice(index, 1)"
                  class="selected-tag"
              >
                {{ tag }}
              </el-tag>
              <el-input
                  v-model="newTag"
                  class="tag-input"
                  placeholder="输入标签后按回车添加"
                  @keyup.enter.native="handleAddTag"
                  size="small"
                  :disabled="formData.tags.length >= 5"
                  :prefix-icon="Plus"
              ></el-input>
            </div>
            <div v-if="formData.tags.length >= 5" class="tag-limit-hint">
              <el-text type="danger" size="small">
                <el-icon><Warning /></el-icon>
                最多只能选择5个标签
              </el-text>
            </div>
          </el-card>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button
              type="primary"
              @click="createStory"
              size="large"
              :icon="Promotion"
              class="action-btn"
          >
            生成故事
          </el-button>
          <el-button
              @click="resetForm"
              size="large"
              :icon="Refresh"
              class="action-btn"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog
        title="提示"
        v-model="dialogVisible"
        :show-close="false"
        width="400px"
        align-center
    >
      <div style="text-align: center;">
        <el-icon size="24" :color="dialogMessage.includes('成功') ? '#67C23A' : '#F56C6C'">
          <component :is="dialogMessage.includes('成功') ? CircleCheck : Warning" />
        </el-icon>
        <span style="margin-left: 10px;">{{ dialogMessage }}</span>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">确定</el-button>
      </template>
    </el-dialog>

    <div v-loading="loading"
         element-loading-text="AI正在努力创作中，请稍候..."
         element-loading-background="rgba(0, 0, 0, 0.7)"
         element-loading-spinner="el-icon-loading">
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeUnmount } from 'vue'
import { storeToRefs } from 'pinia'
import axios from '../api/index.js'
import { userStore } from "../store/UserStore.js"
import {
  Calendar,
  ChatDotRound,
  ChatLineSquare,
  CircleCheck,
  DataAnalysis,
  Delete,
  Document,
  Edit,
  MagicStick,
  Notebook,
  Picture,
  Plus,
  Promotion,
  Reading,
  Refresh,
  Upload,
  Warning
} from '@element-plus/icons-vue'

// 状态定义
const formData = reactive({
  title: '',
  content: ref(''),
  type: '故事',
  tags: [],
})

const askText = ref('')
const askImgText = ref('')
const imageCount = ref(1)
const imageUrls = ref([])
const checkImageTimer = ref(null)
const uploadedImageUrl = ref('')
const file = ref(null)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogMessage = ref('')
const newTag = ref('')

const defaultTags = ['原创', '热门', '情感', '科幻', '生活', '哲理']

// Store
const store = userStore()
const { cur_user } = storeToRefs(store)

// 方法定义
const aiAskTxt = async () => {
  if (!askText.value) {
    showDialog('请输入AI创作内容')
    return
  }

  formData.content = ''
  loading.value = true

  try {
    const abortController = new AbortController()
    const channel = await fetch(axios.getUri() + '/ai/text/create', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream',  // ← 缺失这行
        'Authorization': 'Bearer ' + localStorage.getItem('jwt'),
      },
      body: JSON.stringify({
        ask: askText.value,
        type: formData.type
      }),
      signal: abortController.signal
    })

    if (!channel.ok) {
      throw new Error(`HTTP error! status: ${channel.status}`)
    }

    const reader = channel.body.getReader()
    const decoder = new TextDecoder('utf-8')

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim()
          if (data) {
            formData.content += data
          }
        } else if (line.trim()) {
          formData.content += line.trim()
        }
      }
    }
  } catch (error) {
    console.error('AI创作失败:', error)
    showDialog(error || 'AI创作失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleFileUpload = (rawFile) => {
  file.value = rawFile.raw
  const reader = new FileReader()
  reader.onload = (e) => {
    uploadedImageUrl.value = e.target.result
  }
  reader.readAsDataURL(file.value)
}

const removeUploadedImage = () => {
  file.value = null
  uploadedImageUrl.value = ''
}

const aiAskImg = async () => {
  if (!askImgText.value) {
    showDialog('请输入作图描述')
    return
  }

  if (checkImageTimer.value) {
    clearInterval(checkImageTimer.value)
    checkImageTimer.value = null
  }

  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('ask', askImgText.value)
    params.append('num', imageCount.value)

    const taskId = await axios.post('/ai/image/create2', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })

    if (!taskId) {
      throw new Error('未获取到任务ID')
    }

    checkImageTimer.value = setInterval(() => {
      checkImageStatus(taskId)
    }, 2000)
  } catch (error) {
    console.error('AI作图请求失败:', error)
    showDialog('AI作图请求失败，请重试')
    loading.value = false
  }
}

const checkImageStatus = async (taskId) => {
  try {
    const images = await axios.get('/ai/image/imgstatus', {
      params: { taskId }
    })

    console.log('接收的图片数组：', images, '长度：', images.length)
    if (images && images.length > 0) {
      imageUrls.value = images
      clearInterval(checkImageTimer.value)
      checkImageTimer.value = null
      loading.value = false
    }
  } catch (error) {
    console.error('查询图片状态失败:', error)
    showDialog('图片生成失败，请重试')
    clearInterval(checkImageTimer.value)
    checkImageTimer.value = null
    loading.value = false
  }
}

const removeImage = (index) => {
  imageUrls.value.splice(index, 1)
}

const addDefaultTag = (tag) => {
  if (formData.tags.length >= 5) {
    showDialog('最多只能选择5个标签')
    return
  }

  if (!formData.tags.includes(tag)) {
    formData.tags.push(tag)
  }
}

const handleAddTag = () => {
  if (formData.tags.length >= 5) {
    showDialog('最多只能选择5个标签')
    return
  }

  if (newTag.value && !formData.tags.includes(newTag.value)) {
    formData.tags.push(newTag.value)
    newTag.value = ''
  }
}

const createStory = async () => {
  if (!formData.title || !formData.content) {
    showDialog('标题和内容不能为空')
    return
  }

  loading.value = true
  try {
    const formDataObj = new FormData()
    formDataObj.append('title', formData.title)
    formDataObj.append('cgyName', formData.type)
    formDataObj.append('keyword', formData.tags.join(','))
    formDataObj.append('content', formData.content)
    formDataObj.append('userId', cur_user.value?.id || '')
    formDataObj.append('ai_img_url', imageUrls.value.join(',') || '')

    if (file.value) {
      formDataObj.append('pic', file.value)
    }

    console.log('file:', file.value)
    const response = await axios.post('/creation/publish', formDataObj)
    console.log('response:', response)
    showDialog('故事创建成功')
  } catch (error) {
    console.error('创建故事失败:', error)
    showDialog('创建失败，请重试')
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  Object.assign(formData, {
    title: '',
    content: '',
    type: '故事',
    tags: [],
  })
  askText.value = ''
  askImgText.value = ''
  newTag.value = ''
  uploadedImageUrl.value = ''
  file.value = null
  imageUrls.value = []
}

const showDialog = (message) => {
  dialogMessage.value = message
  dialogVisible.value = true
}

// 生命周期
onBeforeUnmount(() => {
  if (checkImageTimer.value) {
    clearInterval(checkImageTimer.value)
  }
})
</script>

<style scoped>

.creation-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.creation-card {
  max-width: 900px;
  margin: 0 auto;
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  display: flex;
  align-items: center;
  color: #2c3e50;
  margin: 0;
  font-weight: 600;
}

.title-icon {
  margin-right: 10px;
  color: #409EFF;
}

.creation-form {
  padding: 10px 0;
}

.sub-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  background-color: #fafbfc;
}

.full-width-btn {
  width: 100%;
}

.image-preview {
  margin-top: 15px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
}

.images-preview {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.thumbnail {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.thumbnail:hover {
  transform: scale(1.03);
}

.preview-actions {
  display: flex;
  justify-content: center;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.default-tags {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-section-title {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  margin-right: 5px;
}

.default-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.default-tag:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.default-tag.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.added-tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.selected-tag {
  transition: all 0.3s;
}

.selected-tag:hover {
  transform: scale(1.05);
}

.tag-input {
  width: 180px;
}

.tag-limit-hint {
  margin-top: 5px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px dashed #e4e7ed;
}

.action-btn {
  min-width: 120px;
  margin: 0 10px;
}

.upload-demo {
  width: 100%;
}

.el-upload__tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .creation-container {
    padding: 10px;
  }

  .creation-card {
    border-radius: 8px;
  }

  .images-preview {
    grid-template-columns: repeat(2, 1fr);
  }

  .form-actions {
    flex-direction: column;
    gap: 10px;
  }

  .action-btn {
    width: 100%;
    margin: 5px 0;
  }
}
</style>